<template>
  <div>
    <el-upload
      ref="hiddenUpload"
      class="hidden-upload"
      :action="uploadImg"
      :headers="headers"
      :show-file-list="false"
      :on-success="handleUploadSuccess"
    ></el-upload>
    <QuillEditor
      v-model:content="localContent"
      :options="editorOptions"
      contentType="html"
      ref="quillEditor"
    />
  </div>
</template>

<script>
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";

export default {
  components: { QuillEditor },
  props: {
    content: {
      type: String,
      default: "",
    },
    uploadImg: String,
    headers: Object,
    imgServer: String,
  },
  data() {
    return {
      localContent: this.content,
      editorOptions: {
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ script: "sub" }, { script: "super" }],
              [{ indent: "-1" }, { indent: "+1" }],
              [{ direction: "rtl" }],
              [{ size: ["small", false, "large", "huge"] }],
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ color: [] }, { background: [] }],
              [{ font: [] }],
              [{ align: [] }],
              ["clean"],
              ["link", "image", "video"],
            ],
            handlers: {
              image: this.handleImageClick,
            },
          },
        },
      },
    };
  },
  watch: {
    content(newVal) {
      if (newVal !== this.localContent) {
        this.localContent = newVal;
      }
    },
    localContent(newVal) {
      this.$emit("update:content", newVal);
    },
  },
  methods: {
    handleImageClick() {
      this.$refs.hiddenUpload.$el.querySelector("input[type=file]").click();
    },
    handleUploadSuccess(response) {
      const quill = this.$refs.quillEditor.getQuill();
      const range = quill.getSelection();
      if (range) {
        quill.insertEmbed(
          range.index,
          "image",
          this.imgServer + response.files[0]
        );
        quill.setSelection(range.index + 1);
      }
    },
    // 新增方法，用于清空编辑器内容
    clearEditorContent() {
      const quill = this.$refs.quillEditor.getQuill();
      quill.setText(""); // 清空文本内容
      quill.deleteText(0, quill.getLength()); // 确保完全清空
      this.localContent = ""; // 更新本地绑定内容
    },
  },
};
</script>

<style scoped>
.hidden-upload {
  display: none;
}
</style>
